<template>
  <div class="app-container">

    <el-button type="primary" @click="dialogFormVisible = true">新增一条新闻</el-button>

    <br><br>

    <el-dialog title="新闻表单" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="formName">
        <el-form-item label="新闻标题" :label-width="formLabelWidth" prop="newsTitle">
          <el-input v-model="form.newsTitle" autocomplete="on" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="新闻内容" :label-width="formLabelWidth" prop="newsContent">
          <el-input v-model="form.newsContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="新闻类型" :label-width="formLabelWidth" prop="typeName">
          <el-select v-model="form.typeName" filterable placeholder="请选择新闻类型">
            <!-- <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option> -->
            <el-option label="体育" value="体育" />
            <el-option label="新能源" value="新能源" />
          </el-select>
        </el-form-item>
        <el-form-item label="新闻发布者" :label-width="formLabelWidth" prop="newsPublishers">
          <el-input v-model="form.newsPublishers" autocomplete="on" placeholder="请输入发布者" />
        </el-form-item>
        <!-- <el-form-item label="新闻图片" :label-width="formLabelWidth">
          <el-input v-model="form.newsPic" autocomplete="on" />
        </el-form-item> -->
        <el-form-item label="新闻图片" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            drag
            action="http://localhost:8888/news/upload"
            multiple
            name="pic">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item>
          <el-upload
            action="http://localhost:8888/news/uploads"
            list-type="picture-card"
            :auto-upload="false">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <i class="el-icon-download"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item> -->


        
        <el-form-item label="新闻级别" :label-width="formLabelWidth" prop="newsRate">
          <el-radio-group v-model="form.newsRate">
            <el-radio label="1">一般</el-radio>
            <el-radio label="2">中等</el-radio>
            <el-radio label="3">重要</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm(form)">重置</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onsubmit(form)">确 定</el-button>
      </div>
    </el-dialog>


  

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="新闻编号" width="95">
        <template slot-scope="scope">
          {{ scope.row.newsId }}
        </template>
      </el-table-column>
      <el-table-column label="新闻标题" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.newsTitle }}
        </template>
      </el-table-column>
      <el-table-column label="新闻内容" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.newsContent }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="新闻类型id" align="center" width="80">
        <template slot-scope="scope">
          {{ scope.row.typeId }}
        </template>
      </el-table-column> -->
      <el-table-column label="新闻类型" align="center" width="120">
        <template slot-scope="scope">
          {{ scope.row.typeName }}
        </template>
      </el-table-column>
      <el-table-column label="新闻发布者" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.newsPublishers }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="发布时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.pubTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="新闻图片" width="110" align="center">
          <!-- <template slot-scope="scope">
          <img :src="scope.row.newsPic">
                    <span>{{ scope.row.newsPic }}</span>
          <img class="pic-404__parent" src="../../assets/pic/4.png" alt="404"> 
        </template>  --> 
        <!-- <template slot-scope="scope">
          <el-image
            class="table-td-thumb"
            :src="require('../../assets/pic/' + scope.row.newsPic )"
          />
        </template> -->
      <template slot-scope="scope">
          <el-image
            class="table-td-thumb"
            :src="scope.row.newsPic == 'undefined' ? require('../../assets/pic/1.png') : require('../../assets/pic/' + scope.row.newsPic ) "
          />
          <!-- :src="[
            $route.path == '/home'
              ? require('../assets/image/statistical_2.png')
              : require('../assets/image/statistical_1.png'),
          ]" -->
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="新闻级别" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.newsRate | statusFilter">{{ scope.row.newsRate }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteNews(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
//import { statement } from '@babel/template';
import axios from 'axios';
import { Message } from 'element-ui';
import path from 'path';

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        3: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      
      dialogTableVisible: false,
      dialogFormVisible: false,
      formInit: {
        newsTitle: '',
        typeName: '',
        newsContent: "",
        newsPublishers: "",
        newsPic: "",
        newsRate: "1"
      },
      form: {
        newsTitle: '',
        typeName: '',
        newsContent: "",
        newsPublishers: "",
        newsPic: "",
        newsRate: "1"
      },
      formLabelWidth: '120px',
      
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      rules: {
          newsTitle: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ],
          newsContent: [
            { required: true, message: '请输入内容', trigger: 'blur' }
          ],
          newsPublishers: [
            { required: true, message: '请输入发布者', trigger: 'blur' }
          ],
          newsRate: [
            { required: true, message: '请输入内容', trigger: 'blur' }
          ],
          typeName: [
            { required: true, message: '请选择新闻类型', trigger: 'blur'}
          ]
      }
    }
  },
  created() {
    this.fetchData()
    console.log("开始了");

  },
  methods: {
    fetchData() {
      this.listLoading = true
      
      axios.get("http://localhost:8888/news").then((result)=>{
      this.list = result.data.data;
      this.listLoading = false;
      
    console.log(this.list);
    })
    },
        // 格式化表格消息内容
        stateFormat(row, column, cellValue) {
      // console.log(row , column , cellValue)
      if (!cellValue) return "";
      if (cellValue.length > 4) {
        //最长固定显示4个字符
        return cellValue.slice(0, 4) + "...";
      }
      return cellValue;
    },

    onsubmit(formName){
      console.log("formName", formName);
      this.$refs.formName.validate((valid) => {
          if (valid) {
            
            let formData = new FormData();
            /* 获取图片URL，通过请求pic表 */
            axios.get("http://localhost:8888/news/listPic").then((result)=>{
              this.form.newsPic = result.data.data[0];
          //console.log(this.form);
              for(var key in this.form){
                  formData.append(key,this.form[key]);
                }
                /* 提交表单 */
                axios({
                method:"post",
                url:"http://localhost:8888/news",
                headers: {
                "Content-Type": "multipart/form-data"
                },
                data:formData
            }).then((res)=>{
                      this.dialogFormVisible = false;
                      console.log(res);
                      this.fetchData();
                      this.form = this.formInit;
                      this.open2();
                      /* 清空pic表 */
                      axios.delete("http://localhost:8888/news/deletePic");
                  });
                //console.log(formData);
              });
                
          
          } else {
            console.log('error submit!!');
            this.open1();

            return false;
          }
        });


    },
    resetForm(formName) {
      if(this.$refs.formName !== undefined) {
        this.$refs.formName.resetFields();
      }
        
      },



    deleteNews(index){
      let deleteId = this.list[index].newsId;
      let deleteTitie = this.list[index].newsTitle;
      console.log(deleteId);
      this.$confirm(`确认删除 "${deleteTitie}" 这条数据？`).then(async()=>{
        axios({
	    method:"delete",
	    url:"http://localhost:8888/news/" + deleteId,
	    headers: {
		  "Content-Type": "multipart/form-data"
	    }
	}).then((res)=>{
            console.log(res);
            this.fetchData();
            Message.success(`删除 "${deleteTitie}" 成功`)
        });

      })
      
    },


    handleRemove(file) {
        console.log(file);
      },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },

    /* 消息弹框 */
    open1() {
        const h = this.$createElement;

        this.$notify.error({
          title: '内容错误',
          message: h('i', { style: 'color: teal'}, '请补全表单再次提交')
        });
      },
    open2() {
      const h = this.$createElement;

      this.$notify({
        title: '提交成功',
        message: h('i', { style: 'color: teal'}, '成功添加一条新闻'),
        type: 'success'
      });
    },

  }


  
}
</script>
 <!-- eslint-disable --> 